﻿using Microsoft.EntityFrameworkCore;
using YougeBookmark.DataAccess;
using YougeBookmark.Models;

namespace YougeBookmark.Business.Services;

/// <summary>
/// 标签管理服务类
/// </summary>
public class TagService
{
    private readonly AppDbContext _context;

    public TagService(AppDbContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 创建新标签
    /// </summary>
    /// <param name="name">标签名称</param>
    /// <param name="colorCode">颜色代码</param>
    /// <returns>新创建的标签对象</returns>
    public Tag CreateTag(string name, string colorCode = "#4CAF50")
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("标签名称不能为空");

        if (_context.Tags.Any(t => t.Name == name))
            throw new ArgumentException($"标签名称'{name}'已存在");

        var newTag = new Tag
        {
            Name = name.Trim(),
            ColorCode = colorCode,
            CreatedAt = DateTime.Now
        };

        _context.Tags.Add(newTag);
        _context.SaveChanges();
        return newTag;
    }

    /// <summary>
    /// 获取所有标签（分页）
    /// </summary>
    /// <param name="page">页码</param>
    /// <param name="pageSize">每页数量</param>
    /// <returns>标签列表及总数</returns>
    public (List<Tag>, int) GetAllTags(int page = 1, int pageSize = 10)
    {
        var query = _context.Tags
            .OrderByDescending(t => t.CreatedAt);

        var total = query.Count();
        var items = query
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToList();

        return (items, total);
    }

    /// <summary>
    /// 更新标签信息
    /// </summary>
    public Tag UpdateTag(int tagId, string newName, string newColorCode)
    {
        var tag = _context.Tags.Find(tagId)
            ?? throw new InvalidOperationException("未找到指定标签");

        if (_context.Tags.Any(t => t.Name == newName && t.Id != tagId))
            throw new ArgumentException($"名称'{newName}'已被其他标签使用");

        tag.Name = newName.Trim();
        tag.ColorCode = newColorCode;
        _context.SaveChanges();
        return tag;
    }

    /// <summary>
    /// 删除标签（带使用检查）
    /// </summary>
    public void DeleteTag(int tagId)
    {
        if (CheckTagUsage(tagId))
            throw new InvalidOperationException("该标签已被书签使用，无法删除");

        var tag = _context.Tags.Find(tagId)
            ?? throw new InvalidOperationException("未找到指定标签");

        _context.Tags.Remove(tag);
        _context.SaveChanges();
    }

    /// <summary>
    /// 检查标签是否被书签使用
    /// </summary>
    public bool CheckTagUsage(int tagId)
    {
        return _context.Bookmarks
            .Any(b => b.Tags.Contains(tagId.ToString()));
    }

    /// <summary>
    /// 根据名称搜索标签
    /// </summary>
    public List<Tag> SearchTags(string keyword, int page = 1, int pageSize = 10)
    {
        return _context.Tags
            .Where(t => EF.Functions.Like(t.Name, $"%{keyword}%"))
            .OrderBy(t => t.Name)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToList();
    }

    /// <summary>
    /// 获取标签颜色字典（用于UI渲染）
    /// </summary>
    public Dictionary<int, string> GetTagColorDictionary()
    {
        return _context.Tags
            .ToDictionary(t => t.Id, t => t.ColorCode);
    }


    /// <summary>
    /// 根据标签ID获取标签名称（带缓存机制）
    /// </summary>
    public string GetTagNameById(int tagId)
    {
        // 初始化标签缓存（如果尚未加载）
        if (_tagCache == null || !_tagCache.Any())
        {
            RefreshTagCache();
        }

        // 从缓存获取标签名称
        return _tagCache.TryGetValue(tagId, out var tag)
            ? tag.Name
            : "未知标签";
    }

    /// <summary>
    /// 根据标签ID获取完整标签对象（带自动缓存刷新）
    /// </summary>
    public Tag GetTagById(int tagId)
    {
        // 优先从缓存获取
        if (_tagCache != null && _tagCache.ContainsKey(tagId))
        {
            return _tagCache[tagId];
        }

        // 缓存未命中时从数据库加载
        var tag = _context.Tags.Find(tagId);
        if (tag != null)
        {
            _tagCache[tagId] = tag;
        }
        return tag ?? new Tag { Name = "已删除标签", ColorCode = "#CCCCCC" };
    }

    /// <summary>
    /// 刷新标签缓存
    /// </summary>
    public void RefreshTagCache()
    {
        _tagCache = _context.Tags
            .AsNoTracking()
            .ToDictionary(t => t.Id, t => t);
    }

    // 在类顶部添加缓存字段
    private static Dictionary<int, Tag> _tagCache;


}